package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.CourseDao;
import com.itheima.domain.Course;
import com.itheima.service.CourseService;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;
import java.util.List;
import java.util.UUID;

public class CourseServiceImpl implements CourseService {
    @Override
    public PageInfo findByPage(int currentPage) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CourseDao mapper = sqlSession.getMapper(CourseDao.class);
        PageHelper.startPage(currentPage,5);
        List<Course> list = mapper.findAll();
        PageInfo pageInfo = new PageInfo(list);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public void delete(String courseId) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CourseDao mapper = sqlSession.getMapper(CourseDao.class);
        mapper.delete(courseId);
        sqlSession.close();
    }

    @Override
    public void add(Course course) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CourseDao mapper = sqlSession.getMapper(CourseDao.class);
        String id = UUID.randomUUID().toString();
        course.setId(id);
        course.setCreateTime(new Date());
        mapper.add(course);
        sqlSession.close();
    }

    @Override
    public void update(Course course) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CourseDao mapper = sqlSession.getMapper(CourseDao.class);
        course.setUpdateTime(new Date());
        mapper.update(course);
        sqlSession.close();
    }
}
